(() => {
    // 生活终于要对我这只小猫咪🐱下手了～
    // https://detail.m.tmall.com/item.htm?id=20739895092&skuId=4227830352490
    const moument = '2019-11-08 20:00'; // 抢购时间

    const ms = +new Date(moument); // 抢购时间毫秒值
    const pre = +new Date(ms - 1000 * 5); // 提前 5 秒钟准备
    const end = +new Date(ms + 1000 * 60 * 1); // 一分钟之后结束

    // 获取服务器时间戳
    const getServerTime = async () => {
        return +new Date((await fetch(`#${ +new Date() }`, {
            method: 'head',
        }).then((res) => res.headers)).get("Date"));
    };

    const cartBtn = document.querySelector('div.trade > a.cart'); // 加购
    const buyBtn = document.querySelector('div.trade > a.buy'); // 购买

    const removeClass = (dom, className) => {
        if (dom.classList.contains(className)) {
            dom.classList.remove(className);
        }
    };

    // 咱也没买过茅台，不知道是不是这个流程
    const doTask = () => {
        removeClass(cartBtn, 'disabled');
        removeClass(buyBtn, 'disabled');
        buyBtn.click()
        setTimeout(() => {
            const okBtn = document.querySelector('div.trade > a.ok'); // 确定
            const numberInput = document.querySelector('input#number'); // 数量

            removeClass(okBtn, 'disabled');
            numberInput.value = 2;
            okBtn.click();

            setTimeout(() => {
                // 取决于你的网速
                const submitBtn = document.querySelector('#submitBlock_1 > div > div > div > div:nth-child(3)');
                // FIXME ??
                submitBtn.click();
            }, 1800);
        }, 200);
    };

    const intervalId = setInterval(() => {
        getServerTime().then(now => {
            console.log(`server time: ${ now }`);
            // 结束了
            if (now >= end) {
                console.info(`it's time to end.`);
                clearInterval(intervalId);
                return;
            }
            // 准备时间
            if (now >= pre) {
                console.log(`it's time to go...`);
                if (now >= ms) {
                    doTask();
                }
            } else {
                console.info(`it's too early.`);
                clearInterval(intervalId);
                return;
            }
        });
    }, 800);
})();
